package com.all.seria.serialize.kryo;

import com.all.seria.serialize.Serializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author LY
 * @create 2024/5/10 15:01
 * @Description kryo序列化
 */
public class KryoSerializer implements Serializer {

    @Override
    public <T> byte[] serialize(T obj) {
        if (obj == null){
            throw new RuntimeException("serialize object is null");
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             final Output output = new Output(baos)
        ) {
            Kryo kryo = new Kryo();
            kryo.setReferences(false);
            kryo.register(obj.getClass(), new JavaSerializer());
            //进行序列化
            kryo.writeClassAndObject(output, obj);
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Serialization failed");
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) {
        if (data == null){
            throw new RuntimeException("deserialize data is null");
        }
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
             Input input = new Input(byteArrayInputStream)) {
            Kryo kryo = new Kryo();
            kryo.setReferences(false);
            kryo.register(cls, new JavaSerializer());
            return (T) kryo.readClassAndObject(input);
        } catch (IOException e) {
            throw new RuntimeException("Serialization failed");
        }
    }
}
